package com.hitqz.robot.biz.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.hitqz.robot.api.business.dto.RobotSendClientMsgDto;
import com.hitqz.robot.api.business.dto.UpdateClientWarningDto;
import com.hitqz.robot.api.business.entity.PatrolResultEntity;
import com.hitqz.robot.api.business.entity.RobotEntity;
import com.hitqz.robot.api.business.entity.RobotWarningRecordEntity;
import com.hitqz.robot.api.business.vo.RobotWarningRecordVo;
import com.hitqz.robot.api.dispatch.protocol.ProtocolEnum;
import com.hitqz.robot.biz.service.PatrolResultService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.biz.service.RobotWarningRecordService;
import com.hitqz.robot.common.core.util.R;
import com.hitqz.robot.common.security.service.RobotUser;
import com.hitqz.robot.common.security.util.SecurityUtils;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 报警记录
 *
 * @author wengyongxin
 * @date 2024-05-12 03:21:06
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/warning")
@Tag(description = "warning", name = "报警管理")
@Slf4j
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class RobotWarningRecordController {

    private final RobotWarningRecordService robotWarningRecordService;

    private final RobotService robotService;

    private final PatrolResultService patrolResultService;


    /**
     * 分页查询
     *
     * @param page               分页对象
     * @param robotWarningRecord 报警记录
     * @return
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page")
//    @PreAuthorize("@pms.hasPermission('warning_view')" )
    public R<Page<RobotWarningRecordVo>> getRobotWarningRecordPage(@ParameterObject Page page, @ParameterObject RobotWarningRecordEntity robotWarningRecord) {
        LambdaQueryWrapper<RobotWarningRecordEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StrUtil.isNotBlank(robotWarningRecord.getType()), RobotWarningRecordEntity::getType, robotWarningRecord.getType());
        wrapper.like(StrUtil.isNotBlank(robotWarningRecord.getTitle()),
                RobotWarningRecordEntity::getTitle, robotWarningRecord.getTitle());
        wrapper.eq(Objects.nonNull(robotWarningRecord.getTime()),
                RobotWarningRecordEntity::getTime, robotWarningRecord.getTime());
        wrapper.eq(Objects.nonNull(robotWarningRecord.getLevel()),
                RobotWarningRecordEntity::getLevel, robotWarningRecord.getLevel());
        wrapper.orderByDesc(RobotWarningRecordEntity::getId);
        wrapper.orderByDesc(RobotWarningRecordEntity::getTime);
        Page<RobotWarningRecordEntity> robotWarningRecordEntityPage = robotWarningRecordService.page(page, wrapper);
        Page<RobotWarningRecordVo> voPage = new Page<>();
        BeanUtil.copyProperties(robotWarningRecordEntityPage, voPage, false);

        List<RobotWarningRecordVo> vos = Lists.newArrayList();

        for (RobotWarningRecordEntity record : robotWarningRecordEntityPage.getRecords()) {
            RobotWarningRecordVo vo = new RobotWarningRecordVo();
            BeanUtil.copyProperties(record, vo, false);
            vos.add(vo);
        }
        voPage.setRecords(vos);
        return R.ok(voPage);
    }


    /**
     * 通过id查询报警记录
     *
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/{id}")
//    @PreAuthorize("@pms.hasPermission('warning_view')" )
    public R getById(@PathVariable("id") Long id) {
        return R.ok(robotWarningRecordService.getById(id));
    }

    /**
     * 新增报警记录
     *
     * @param robotWarningRecord 报警记录
     * @return R
     */
    @Operation(summary = "新增报警记录", description = "新增报警记录")
//    @SysLog("新增报警记录" )
    @PostMapping
//    @PreAuthorize("@pms.hasPermission('warning_add')" )
    public R save(@RequestBody RobotWarningRecordEntity robotWarningRecord) {
        return R.ok(robotWarningRecordService.save(robotWarningRecord));
    }

    /**
     * 修改报警记录
     *
     * @param robotWarningRecord 报警记录
     * @return R
     */
    @Operation(summary = "修改报警记录", description = "修改报警记录")
//    @SysLog("修改报警记录" )
    @PutMapping
//    @PreAuthorize("@pms.hasPermission('warning_edit')" )
    public R updateById(@RequestBody RobotWarningRecordEntity robotWarningRecord) {
//        RobotWarningRecordEntity db = robotWarningRecordService.getById(robotWarningRecord.getId());
        robotWarningRecord.setFlag("1");
        String name = SecurityUtils.getAuthentication().getName();
        robotWarningRecord.setOperator(name);
        robotWarningRecord.setAuditor(name);
//        Long patrolResultId = db.getPatrolResultId();
//        log.info("报警记录{}对应巡检记录:{}", robotWarningRecord.getId(), patrolResultId);
//        if (patrolResultId !=null){
//            PatrolResultEntity patrolResultEntity = patrolResultService.getById(patrolResultId);
//            if (patrolResultEntity!=null){
//                String remark = "原因:"+robotWarningRecord.getCause()+",解决方法:"+robotWarningRecord.getApproach()
//                        +"\n内操:"+robotWarningRecord.getAuditor()+",外操:"+robotWarningRecord.getOperator();
//                patrolResultEntity.setAuditRemark(remark);
//                patrolResultEntity.setUploadStatus(1);
//                patrolResultService.updateById(patrolResultEntity);
//                log.info("更新巡检记录:{}",patrolResultEntity.getId());
//            }
//        }
        return R.ok(robotWarningRecordService.updateById(robotWarningRecord));
    }

    /**
     * 通过id删除报警记录
     *
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除报警记录", description = "通过id删除报警记录")
//    @SysLog("通过id删除报警记录" )
    @DeleteMapping
//    @PreAuthorize("@pms.hasPermission('warning_del')" )
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(robotWarningRecordService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     *
     * @param robotWarningRecord 查询条件
     * @param ids                导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
//    @PreAuthorize("@pms.hasPermission('warning_export')" )
    public List<RobotWarningRecordEntity> export(RobotWarningRecordEntity robotWarningRecord, Long[] ids) {
        return robotWarningRecordService.list(Wrappers.lambdaQuery(robotWarningRecord).in(ArrayUtil.isNotEmpty(ids), RobotWarningRecordEntity::getId, ids));
    }


    @GetMapping(value = "read/{id}")
    @Operation(summary = "某条告警已经读取")
    public R read(@PathVariable Integer id) {
        RobotWarningRecordEntity sysWarning = robotWarningRecordService.getById(id);
        if (sysWarning == null) {
            return R.failed("data not found");
        }
        sysWarning.setFlag("1");
        robotWarningRecordService.updateById(sysWarning);
        return R.ok();
    }


    @GetMapping(value = "readAll")
    @Operation(summary = "全部告警读取")
    public R readAll() {
        String name = SecurityUtils.getAuthentication().getName();
        robotWarningRecordService.update(Wrappers.<RobotWarningRecordEntity>lambdaUpdate()
                .set(RobotWarningRecordEntity::getFlag, "1")
                .set(RobotWarningRecordEntity::getOperator, name)
                .set(RobotWarningRecordEntity::getAuditor, name)
                .set(RobotWarningRecordEntity::getApproach, "已读")
                .eq(RobotWarningRecordEntity::getFlag, "0"));
        return R.ok();
    }


    @GetMapping(value = "/client/{clientId}/read/{id}")
    @Operation(summary = "执行端某条告警已经读取")
    public R clientRead(@PathVariable String clientId, @PathVariable Long id) {
        UpdateClientWarningDto updateWarningDto = new UpdateClientWarningDto();
        updateWarningDto.setClientId(clientId);
        updateWarningDto.setId(id);
        updateWarningDto.setStatus(1);
        RobotSendClientMsgDto msgDto = new RobotSendClientMsgDto();
        msgDto.setCmd(ProtocolEnum.ROBOT_CTRL_CMD.getCmd());
        msgDto.setClientId(clientId);
        msgDto.setData(updateWarningDto);
        SpringUtil.getApplicationContext().publishEvent(msgDto);
        return R.ok();
    }


    @GetMapping(value = "/client/{clientId}/readAll")
    @Operation(summary = "执行端全部告警读取")
    public R clientReadAll(@PathVariable String clientId) {
        UpdateClientWarningDto updateWarningDto = new UpdateClientWarningDto();
        updateWarningDto.setClientId(clientId);
        updateWarningDto.setReadAll(true);
        RobotSendClientMsgDto msgDto = new RobotSendClientMsgDto();
        msgDto.setCmd(ProtocolEnum.ROBOT_CTRL_CMD.getCmd());
        msgDto.setClientId(clientId);
        msgDto.setData(updateWarningDto);
        SpringUtil.getApplicationContext().publishEvent(msgDto);
        return R.ok();
    }


}